# -*- coding: UTF-8 -*-

from datetime import datetime
import sys
from sqlalchemy import and_,  func, or_
from typing import Dict, List, Any, Generator

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Index, Table, ForeignKey, text, JSON, TEXT, distinct
from sqlalchemy.orm import Session, relationship
from common.database import Base
from common.database import SessionMixin
from common.utils import is_empty
from core.logger import logger



__all__ = ['MonitorLogHttpUrl']

class MonitorLogHttpUrl(Base, SessionMixin):
    '''
    接口信息表
    '''
    __tablename__ = "monitor_log_http_url"
    domain = Column(String(64), nullable=False, index=True, comment='域名')
    url = Column(String(256), nullable=False, index=True, comment='url路径')
    method = Column(String(32), nullable=False, index=True, comment='接口方法')
    department = Column(String(32), nullable=False, comment='所属部门')
    production = Column(String(32), nullable=False, comment='所属产品')
    module = Column(String(32), nullable=False, comment='所属模块')
    provider = Column(String(32), nullable=False, comment='服务提供者')
    is_use = Column(Boolean, default=text('true'), comment="是否使用")
    update_at = Column(DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    comment = Column(String(256), nullable=True, comment='接口说明')


    __table_args__ = (
        Index('idx_monitor_log_http_url_domain_url_method', 'domain','url', 'method', unique=True),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic',
        }
    )

    def __repr__(self):
        return f"<monitor_log_http_url='{self.url}'>"


    def object_to_dict(self, db: Session):
        result = {
            key: getattr(self, key)
            for key in self.__mapper__.c.keys()
        }

        return result



    @classmethod
    def get_object_info_for_used(cls, db: Session):
        """
        获取所有正在使用的url信息
        """
        object_info = db.query(cls).filter(
            cls.is_use
        ).to_dict()
        return object_info
    
    
    @classmethod
    def get_object_by_url(cls, db: Session, domain: str, url: str, method: str):
        object = db.query(cls).filter(
            cls.name == name
        ).first()
        return object
    
    @classmethod
    def get_object_info_by_url(cls, db: Session, domain, url, method):
        """
        获取所有正在使用的url信息
        """
        object_info = db.query(cls).filter(
            cls.domain == domain,
            cls.url == url,
            cls.method == method
        ).to_dict_first()
        return object_info